// pages/shop/shop-list.js
const app = getApp();
const util = require('../../utils/util.js');
let _this;
let pageNo = 1, pages = '', limit = 10;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    appLink: app.globalData.appLink,
    newList:[],
    region: ['请选择', '请选择', '请选择'],
    userInfo: app.globalData.xieYouUserInfo,
    userInfoRoot: app.globalData.xieYouUserInfoRoot,
    Maintenance: app.globalData.Maintenance,
    userBrandList: false,// 用户机型列表
    salesSort: true,
    priceSort: false,
    salesOder: 'asc',
    priceOder: 'asc',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    _this = this;
    let data = {}
    options.search ? data.search = options.search:'';
    options.self == 1 ? data.self = options.self:'';
    options.productBrand ? data.productBrand = options.productBrand:'';
    options.cid ? data.cid = options.cid:'';
    options.order ? data.order = 'asc':'';
    options.sort ? data.sort = 'sell_cnt':'';
    _this.setData({
      searchData: data,
      self: options.self == 1 ? true : false
    })
    _this.lint();
  },
  lint:function(){
    _this.list(1,10);
    _this.setData({
      brandModel: app.globalData.xieYouUserInfoRoot.userBrandModel,
      brandsModelList: app.globalData.xieYouUserInfoRoot.userBrandsModel,
      userInfo: app.globalData.xieYouUserInfo,
    })
    _this.getShopCar();
  },
  xieyouSelf:function(e){
    let self = _this.data.self,
      searchData = _this.data.searchData;
    self ? delete (searchData['self']) : searchData.self=1;
    _this.setData({
      searchData: searchData
    })
    _this.list(1,10);
    _this.toggleSwitch(e);
  },
  sortBind:function(e){
    let sort = e.currentTarget.dataset.name,
      searchData = _this.data.searchData,
      salesOder = _this.data.salesOder,
      priceOder = _this.data.priceOder;
    if (sort == 'salesSort'){
      searchData.sort = 'sell_cnt';
      if (salesOder == 'asc'){
        searchData.order = 'desc';
        salesOder = 'desc'
      }else{
        searchData.order = 'asc'
        salesOder = 'asc'
      }
    }else{
      searchData.sort = 'price';
      if (priceOder == 'asc') {
        searchData.order = 'desc'
        priceOder = 'desc'
      } else {
        searchData.order = 'asc'
        priceOder = 'asc'
      }
    }
    _this.setData({
      searchData: searchData,
      priceOder: priceOder,
      salesOder: salesOder
    })
    _this.list(1,10)
  },
  bindRegionChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  //更改用户默认绑定机型
  changeUserBindBrandModel(e) {
    var userBrandModelId = '';
    if (e.target.dataset.modelId) {
      userBrandModelId = e.target.dataset.modelId;
    } else {
      userBrandModelId = e.currentTarget.dataset.modelId;
    }
    var userCode = _this.data.userInfo.code;
    //获取品牌
    app.changeUserBindBrandModel(userCode, userBrandModelId, function (data) {
      if (data == 'SUCCESS') {
        _this.initUserBrandModelFun(userCode)
        }
    });
  },
  // 修改绑定机型数据
  initUserBrandModelFun(code) {
    if (typeof code == 'string') {
      var userCode = code
    } else {
      var userCode = code.code
    }
    app.globalData.xieYouUserInfoRoot.userBrandsModel = [];
    app.globalData.xieYouUserInfoRoot.userBrandModel = null;
    app.initUserBrandModel(userCode, function (data) {
      var dataList = data;
      for (var i = 0; i < data.length; i++) {
        //将用户机型数据存入到全局数组
        app.globalData.xieYouUserInfoRoot.userBrandsModel.push(data[i]);
        // 将选中的机型显示到选择框中
        if (data[i].selected == 1) {
          console.log(data[i]);
          app.globalData.xieYouUserInfoRoot.userBrandModel = data[i]
        }
      }
      var pages = getCurrentPages();
      _this.setData({
        brandModel: app.globalData.xieYouUserInfoRoot.userBrandModel,
        brandsModelList: app.globalData.xieYouUserInfoRoot.userBrandsModel,
      })
      var prevPageThree = pages[0];
      prevPageThree.setData({
        userBrandModel: app.globalData.xieYouUserInfoRoot.userBrandModel,
        brandLogo: app.globalData.xieYouUserInfoRoot.userBrandModel.brand.brandLogo,
        brandModelName: app.globalData.xieYouUserInfoRoot.userBrandModel.brandModel.name
      })

    });
  },
  getShopCar: function () {
    app.getMassage(null, _this.data.userInfo.code, 'getShopCar', function (res) {
      console.log(res);
      _this.setData({
        shopCarId: res.data.id,
      })
    }, 'GET')
  },
  addShopCar: function (e) {
    let index = e.currentTarget.dataset.index,
      detail = _this.data.newList[index],
      data = {
        brandId:null,
        brandName: _this.data.brandModel?_this.data.brandModel.brand.name:'',
        categoryCode:null,
        categoryName:null,
        count:1,
        isAllPick:false,
        leadUserCode:null,
        modelName: _this.data.brandModel ? _this.data.brandModel.brandModel.name:'',
        price: detail.price,
        product: detail,
        productName: detail.name,
        seckill: detail.seckill
        };
    app.getMassage(data, _this.data.shopCarId + '/item/new', 'shopAdd', function (res) {
      if (res.status == 'success') {
        wx.showToast({
          title: '已经加入购物车',
          icon: 'success',
          duration: 2000
        })
      }
    })
  },
  requireNeed:function(e){
    let pName = e.detail.value.pName,
      jName = e.detail.value.jName,
      phone = e.detail.value.phone,
      verifyCode = e.detail.value.verifyCode,
      directions = e.detail.value.directions,
      region = _this.data.region;
    if (phone == '' || phone == null) {
      util.alertMsg('提示', '电话号码不能为空', function () {
        console.log('用户点击确定');
        
        //$state.go('mt.userOrderDetail', {id: res.data[0].id}, true);
      }, function () {
        console.log('用户点击取消');
        
      });
      return;
    }
    if (verifyCode == '' || verifyCode == null) {
      util.alertMsg('提示', '输入验证码', function () {
        console.log('用户点击确定');
        
        //$state.go('mt.userOrderDetail', {id: res.data[0].id}, true);
      }, function () {
        console.log('用户点击取消');
        
      });
      return;
    }
    if (pName == '' || pName == null) {
      util.alertMsg('提示', '配件名称不能为空', function () {
        console.log('用户点击确定');
        
        //$state.go('mt.userOrderDetail', {id: res.data[0].id}, true);
      }, function () {
        console.log('用户点击取消');
        
      });
      return;
    }
    if (jName == '' || jName == null) {
      util.alertMsg('提示', '机型不能为空', function () {
        console.log('用户点击确定');
        
        //$state.go('mt.userOrderDetail', {id: res.data[0].id}, true);
      }, function () {
        console.log('用户点击取消');
        
      });
      return;
    }
    if (region[0] == '请选择') {
      util.alertMsg('提示', '地区不能为空', function () {
        console.log('用户点击确定');
        
        //$state.go('mt.userOrderDetail', {id: res.data[0].id}, true);
      }, function () {
        console.log('用户点击取消');
        
      });
      return;
    }
    if (directions == '' || directions == null) {
      util.alertMsg('提示', '说明不能为空', function () {
        console.log('用户点击确定');
        
        //$state.go('mt.userOrderDetail', {id: res.data[0].id}, true);
      }, function () {
        console.log('用户点击取消');
        
      });
      return;
    }
    let data = {
      address: region[0],
      brandModel: _this.data.brandModel.brand.name + '/' + _this.data.brandModel.brandModel.name,
      category: _this.data.searchData.cid,
      description: directions,
      isForShow: false,
      phone: phone,
      userCode: _this.data.userInfo.code,
      verifyCode: verifyCode
    };
    app.getMassage(data, null, 'requireNeed',function(res){
      if (res.status == 'success'){
        wx.showToast({
          title: '已提交',
          icon: 'success',
          duration: 2000
        })
      }else{
        wx.showToast({
          title: res.massage,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  bindblur:function(e){
    _this.setData({
      phoneNo: e.detail.value
    })
  },
  setNo:function(e){
    let phone = _this.data.phoneNo;
    let data = {
      phone: phone,
      type: null
    }
    if (phone == '' || phone == null) {
      util.alertMsg('提示', '电话号码不能为空', function () {
        console.log('用户点击确定');

        //$state.go('mt.userOrderDetail', {id: res.data[0].id}, true);
      }, function () {
        console.log('用户点击取消');

      });
      return;
    }
    var isPhone = false;
    util.testPhone(phone, function (rs) {
      if (rs) {
        isPhone = true;
      } else {
        isPhone = false;
      }
    });
    if (!isPhone) {
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('警告', '请输入正确的手机号码', function () {
        console.log('用户点击确定')
      }, function () {
        console.log('用户点击取消')
      });
      return;
    }
    app.getMassage(data, null, 'requireYzm', function (res) {
      if (res.status == 'success') {
       console.log(res); 
      }
    },'GET')
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 获取列表
  list: function (page, lim) {
    let url = "commodityList",
      searchData = _this.data.searchData,
      userInfoRoot = _this.data.userInfoRoot,
      userInfo = _this.data.userInfo,
      userArea = _this.data.Maintenance.userArea;
    if (searchData.self == 1){
      searchData.areaCode = userArea.adcode;
    }else{
      searchData.province = userArea.province;
    }
    app.getList(page, lim, searchData, url, function (res) {
      if (res.data) {
        if (page == 1) {
          _this.setData({
            newList: [],
          })
        }
        pageNo = res.data.currentPage / 1 + 1;
        pages = res.data.pageCount;
        var list = res.data.results;
        var newList = _this.data.newList;
        newList = newList.concat(list);
        _this.setData({
          newList: newList,
          pageNo: pageNo,
          pages: pages
        })
      }
    })
  },
  // 滚动触底
  scrolltolower: function () {
    // 判断是否是最后一页
    if (pages >= pageNo) {
      _this.list(pageNo, limit);
    }
  },
  // 去**页
  goNavTo: function (e) {
    app.goNavTo(e, _this.data.buttonClicked, _this);
  },
  // 返回上一页
  goBack: function (e) {
    app.goBack(e, _this.data.buttonClicked, _this);
  },
  // 开关
  toggleSwitch: function (e) {
    app.toggleSwitch(e, _this);
  }
})